import React, { useState, useEffect } from 'react'
import { Row, Col, Input, Button, Avatar, Dropdown, Menu, Popover, Radio,  Modal, Typography, Divider, Form, Select, Space} from 'antd'
import { Editor } from '@bytemd/react'
import {
  FireOutlined,
  LogoutOutlined,
  UserOutlined,
  EditOutlined
} from '@ant-design/icons'
import { storage, errorMsg } from '@/utils/utils'
import Link from 'next/link'
import articlesModel from '../model/articles'
import zhHans from 'bytemd/lib/locales/zh_Hans.json'
import PropTypes from 'prop-types'
import gfm from '@bytemd/plugin-gfm'
import gemoji from '@bytemd/plugin-gemoji'
import highlight from '@bytemd/plugin-highlight-ssr'
import mediumZoom from '@bytemd/plugin-medium-zoom'
import mermaid from '@bytemd/plugin-mermaid'
import UploadFile from '@/components/upload-img'
import { multipartUpload } from '@/utils/oss'
import 'bytemd/dist/index.min.css'
import 'highlight.js/styles/monokai-sublime.css'
import styles from '@/styles/addArticle.module.scss'
import categoriesListModel from 'pages/model/categories-manage'
import { withRouter } from 'next/router'
const plugins = [gfm(), gemoji(), highlight(), mediumZoom(), mermaid()]

const { Title } = Typography
const { Option } = Select
const { TextArea } = Input
function AddArticle () {
  const [value, setValue] = useState('')
  const [visible, setVisible] = useState(false)
  const [form] = Form.useForm()
  const [categoriesList, setCategoriesList] = useState()
  const [tagsList, setTagsList] = useState()
  const [chooseArr, setChooseArr] = useState([])
  const [userInfo, setUserInfo] = useState([])
  // 标题
  const [title, setTitle] = useState(null)
  // const router = useRouter()
  // 封面
  // componentDidMount ( ) {
  //   router.prefetch('/dynamic')
  // }
  const [coverFile, setCoverFile] = useState([])
  useEffect(() => {
    if (storage.get('isLogin') === 1) setUserInfo(JSON.parse(storage.get('next_blog_userInfo')))
  }, [])
  useEffect(() => {
    categoriesListModel.getCategoriesList({
      data: {}
    }).then(({datas}) => {
      if (datas && datas.list) {
        setCategoriesList(datas.list)
      }
    })
    categoriesListModel.getTagsList({
      data: {}
    }).then(({datas}) => {
      if (datas && datas.list) {
        setTagsList(datas.list)
      }
    })
  }, [])
  const changeTag = (value) => {
    setChooseArr(value)
  }
  const handleVisibleChange = (_visible) => {
    // 删除两端空格
    if (title && title.replace(/(^\s*)|(\s*$)/gu, '')) {
      if (value && value.replace(/(^\s*)|(\s*$)/gu, '')) {
        setVisible(_visible)
      } else  {
        errorMsg('内容不能为空~')
      }
    } else  {
      errorMsg('标题不能为空~')
    }  
  }
  const [isModalVisible, setIsModalVisible] = useState(false)
  const handleOk = () => {
    setIsModalVisible(false)
  }

  const handleCancel = () => {
    setIsModalVisible(false)
  }
  // 发布文章
  const postArticle = () => {
    form.validateFields().then(values => {
      articlesModel.addArticle({
        data: {
          userId: userInfo.id,
          title: title,
          content: value,
          categories: values.categories,
          tagsList: values.tagsList,
          coverUrl: coverFile[0]?.url,
          introduction: values.introduction
        }
      }).then(data => {
        if (data.success) {
          setVisible(false)
          articlesModel.addArticleTags({
            data: {
              userId: userInfo.id,
              title: title,
              tagsList: values.tagsList,
              articleId: data.articleId
            }
          }).then(data => {
            if (data.success) setIsModalVisible(true)
          })
        }
      })
    
    })
  }
  const uploadImage = async (files) => {
    const [File] = files
    if (!File) return false
    let imgList = []
    console.log(File)
    if (['image/png', 'image/jpeg', 'image/jpg'].includes(File.type)) {
      await multipartUpload(File, 'image').then((res) => {
        console.log(res)
        if (!res) return false
        imgList.push({
          title: '图片',
          url: res.url
        })
      })
    } else errorMsg('请上传正确的图片格式！')
    return imgList
  }
  const content = (
    <div style={{ width: 600}}>
      <Title level={4}>发布文章</Title>
      <Divider></Divider>
      <Form
        name="basic"
        autoComplete="off"
        labelCol={{span: 4}}
        wrapperCol={{span: 18}}
        form={form}
      >
        <Form.Item
          label="分类"
          name="categories"
          rules={[{ required: true, message: '请选择分类' }]}
        >
          <Radio.Group  buttonStyle="solid">
            <Space style={{flexWrap: 'wrap'}}>
              {
                categoriesList && categoriesList.map(item => <Radio.Button style={{width: 88, textAlign: 'center', marginBottom: 10}} key={item.id} value={item.id}>{item.name}</Radio.Button>)
              }
            </Space>
          </Radio.Group>
        </Form.Item>
        
        <Form.Item
          label={`标签(${4 - chooseArr.length})`}
          name="tagsList"
          rules={[{ required: true, message: '请选择标签' }]}
        >
          <Select placeholder="请选择标签(支持多选、搜索)"  mode="multiple" allowClear onChange={changeTag} filterOption={(input, option) => option.children[1].toLowerCase().indexOf(input.toLowerCase()) >= 0
          }
          optionFilterProp="children"
          >
            {
              tagsList && tagsList.map(item =>  <Option disabled={chooseArr.length >= 4 && chooseArr.indexOf(item.id) === -1} key={item.id} value={item.id}>{item.hotCode === 1 && <FireOutlined style={{color: 'red'}} />}{item.name}</Option>)
            }
          </Select>
        </Form.Item>
        <Form.Item
          label="封面" name="avatarFile"
          trigger="setFileList" validateTrigger="setFileList"
          valuePropName="fileList" 
        >
          <UploadFile fileList={coverFile} setFileList={setCoverFile} fileType="image" mode="oss" maxCount={1} plural={false} tipsContent="建议尺寸：1303*734px，建议3M以内"></UploadFile>
        </Form.Item>
        <Form.Item
          label="摘要"
          name="introduction"
          rules={[{ required: true, message: '请输入摘要' }]}
        >
          <TextArea showCount maxLength={100}   autoSize={{ minRows: 3, maxRows: 5 }} />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 16, span: 18 }} style={{marginTop: 50}}>
          <Button type="default" style={{marginRight: 25}} onClick={() => setVisible(false)}>取 消</Button>
          <Button type="primary" onClick={postArticle} >发布文章</Button>
        </Form.Item>
      </Form>
    </div>
  )
  // 下拉菜单
  const menu = (
    <Menu>
      <Menu.Item key="1">
        <Link href={{pathname: '/add-article'}} prefetch ><span style={{color: '#4e5969'}}> <EditOutlined /> 写文章</span></Link>
      </Menu.Item>
      <Menu.Item key="2">
        <Link href={{pathname: '/my-info'}} prefetch ><span style={{color: '#4e5969'}}> <UserOutlined /> 我的主页</span></Link>
      </Menu.Item>
      <Menu.Item key="3">
        <span style={{color: '#4e5969'}}> <LogoutOutlined /> 退出</span>
      </Menu.Item>
    </Menu>
  )
  const changeTitle = (e) => {
    setTitle(e.target.value)
  }
  return (
    <div className={styles.editor}>
      <Row className={styles.editor_head}>
        <Col span={16}>
          <Input placeholder="请输入标题..." value={title} onChange={(e) => changeTitle(e)} className={styles.input_title} bordered={false} />
        </Col>
        <Col span={8} className="flex j_end">
          {/* <Button type="primary" ghost className="ml_10">草稿箱</Button> */}
          <Popover onVisibleChange={handleVisibleChange} visible={visible} overlay={content} placement="bottomRight" content={content} trigger="click">
            <Button type="primary" className="ml_10" >发布</Button>
          </Popover>
          <Dropdown overlay={menu} placement="bottomCenter" arrow>
            <Avatar  shape="square" className="userAvatar" style={{cursor: 'pointer', marginLeft: 10}} src={userInfo.avatar} size="default" />
          </Dropdown>
        </Col>
      </Row>
      <Row>
        <Col span={24}  className={styles.editor_content}>
          <Editor
            value={value}
            locale={zhHans}
            plugins={plugins}
            onChange={(v) => {
              setValue(v)
            }}
            uploadImages={ async (files) => await uploadImage(files)}
          />
        </Col> 
      </Row>
      <Modal title="提示" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}
        footer={[
          <Link href="/" key="home">
            <Button key="back">
              返回
            </Button>
          </Link>,
          <Button key="submit" type="primary" onClick={() => location.reload()}>
            继续发布
          </Button>,
        ]}
      >
        <p>文章发布成功!</p>
      </Modal>
    </div>
  )
}
AddArticle.propTypes = {
  router: PropTypes.func,
}
export default withRouter(AddArticle)